package com.hellobike.haxing.modules.wms.controller;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.wms.dto.ExportStockPickDto;
import com.hellobike.haxing.modules.wms.dto.StockPickDto;
import com.hellobike.haxing.modules.wms.entity.StockPick;
import com.hellobike.haxing.modules.wms.exception.WmsExportException;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsStockFacade;
import com.hellobike.haxing.modules.wms.service.IStockPickService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
* @Description: t_wms_stock_pick
* @Author: haxing-boot
* @Date:   2020-01-15
* @Version: V1.0
*/
@RestController
@RequestMapping("/wms/stockPick")
@Slf4j
public class StockPickController extends WmsBaseController<StockPick, IStockPickService> {
   @Autowired
   private IStockPickService stockPickService;
   @Autowired
   private WmsStockFacade wmsStockFacade;

   /**
    * 分页列表查询
    *
    * @param stockPick
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "t_wms_stock_pick-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(StockPickDto stockPick,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       stockPick.setWarehouseId(getWarehouseId());
       Page<StockPickDto> page = new Page<>(pageNo, pageSize);
       IPage<StockPickDto> pageList = stockPickService.pageByStockPickDto(page, stockPick);
       if (!CollectionUtils.isEmpty(pageList.getRecords())) {

           pageList.getRecords().forEach(stockPickDto -> {
               if (!StringUtils.isEmpty(stockPickDto.getSpecifications())) {
                   try {
                       JSONArray jsonArray = JSON.parseArray(stockPickDto.getSpecifications());
                       if (jsonArray != null && jsonArray.size() > 0) {
                           for (int i = 0; i < jsonArray.size(); i++) {
                               JSONObject jsonObject = jsonArray.getJSONObject(i);
                               if ("保质期".equals(jsonObject.getString("name"))) {
                                   stockPickDto.setExpiryDate(jsonObject.getString("value"));
                               }
                           }
                       }
                   } catch (Exception ex) {
                       log.error("", ex);
                   }

               }
           });

       }
       return Result.ok(pageList);
   }

   /**
    *   添加
    *
    * @param stockPick
    * @return
    */
   @AutoLog(value = "t_wms_stock_pick-添加",operateType=2)
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody StockPick stockPick) {
       stockPickService.save(stockPick);
       return Result.ok("添加成功！");
   }

   /**
    *  编辑
    *
    * @param stockPick
    * @return
    */
   @AutoLog(value = "t_wms_stock_pick-编辑",operateType=3)
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody StockPick stockPick) {
       stockPickService.updateById(stockPick);
       return Result.ok("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "t_wms_stock_pick-删除",operateType=4)
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       stockPickService.removeById(id);
       return Result.ok("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "t_wms_stock_pick-批量删除",operateType=4)
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.stockPickService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       StockPick stockPick = stockPickService.getById(id);
       if(stockPick==null) {
           return Result.error("未找到对应数据");
       }
       return Result.ok(stockPick);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param stockPick
   */
   @AutoLog(value = "t_wms_stock_pick-导出excel",operateType=6)
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, StockPickDto stockPick) throws WmsExportException {
       try {
           Long warehouseId = getWarehouseId();
           stockPick.setWarehouseId(warehouseId);
           String title = "拣货库存-"+ warehouseId;
           List<ExportStockPickDto> exportList = wmsExportFacade.exportStockPick(stockPick);
           return export(title, ExportStockPickDto.class,exportList);
       } catch (Exception e) {
           throw new WmsExportException(e);
       }
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @AutoLog(value = "t_wms_stock_pick-导入excel",operateType=5)
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, StockPick.class);
   }
    @AutoLog(value = "t_wms_stock_pick-back2MainStock",operateType=3)
    @PostMapping(value = "/back2MainStock")
    public Result<?> back2MainStock(@RequestBody StockPick stockPick) {
        try {
            wmsStockFacade.back2MainStock(stockPick.getId(),getWarehouseId(),getSysUserId());
        } catch (Exception e) {
            log.error("",e);
            return Result.error(e.getMessage());
        }
        return Result.ok("归还成功!");
    }
}
